package models

import "gorm.io/gorm"

type Product struct {
	gorm.Model
	Name       string  `gorm:"type:varchar(100)" json:"name"`
	Price      float64 `gorm:"type:decimal(10,2)" json:"price"`
	Stock      int64   `gorm:"type:int(10)" json:"stock"`
	Ingredient string  `gorm:"type:varchar(255)" json:"ingredient"` //配料
	Taste      string  `gorm:"type:varchar(50)" json:"taste"`       //口味
	Status     int64   `gorm:"type:int(10)" json:"status"`
	ImageUrl   string  `gorm:"type:varchar(255)" json:"imageUrl"`
	Category   int64   `gorm:"type:int(10)" json:"category"`
}

type ProductSearchRequest struct {
	Name     string
	Taste    string
	MaxPrice float64
	MinPrice float64
	Page     int64
	Limit    int64
	Sort     string
}
type ProductSearchResult struct {
	Total    int64     `json:"total"`
	Products []Product `json:"products"`
}

func (p *ProductSearchRequest) ProductSearch(db *gorm.DB) ProductSearchResult {
	if p.Page < 1 {
		p.Page = 1
	}
	if p.Limit > 100 {
		p.Limit = 100
	}
	if p.Limit < 10 {
		p.Limit = 10
	}

	query := DB.Model(&Product{}).Debug()

	if p.Name != "" {
		query = query.Where("name like ?", "%"+p.Name+"%")
	}

	if p.Taste != "" {
		query = query.Where("taste = ?", p.Taste)
	}

	if p.MinPrice > 0 && p.MaxPrice > 0 {
		query = query.Where("price between ? and ?", p.MinPrice, p.MaxPrice)
	}

	switch p.Sort {
	case "price_desc":
		query = query.Order("price desc")

	case "price_asc":
		query = query.Order("price asc")

	case "stock_desc":
		query = query.Order("stock desc")

	case "stock_asc":
		query = query.Order("stock asc")
	default:
		query = query.Order("created_at desc")

	}

	offset := (p.Page - 1) * p.Limit

	var result ProductSearchResult
	query.Offset(int(offset)).Limit(int(p.Limit)).Find(&result.Products)

	query.Count(&result.Total)

	return result
}
